﻿using System;
using System.Runtime.InteropServices;

/// <summary>
/// 
/// </summary>
public class MySendKey
{
    // 引入Windows API中的SendInput函数
    [DllImport("user32.dll", SetLastError = true)]
    static extern uint SendInput(uint nInputs, Input[] pInputs, int cbSize);
    [DllImport("user32.dll", SetLastError = true)]
    public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

    public const byte VK_UP = 0x26;
    public const byte VK_DOWN = 0x28;
    public const byte VK_LEFT = 0x25;
    public const byte VK_RIGHT = 0x27;
    public const byte VK_A = 0x41;

    public const int KEYEVENTF_EXTENDEDKEY = 0x1;
    public const int KEYEVENTF_KEYUP = 0x2;
    [StructLayout(LayoutKind.Sequential)]
    struct Input
    {
        public int type;
        public InputUnion u;
    }

    [StructLayout(LayoutKind.Explicit)]
    struct InputUnion
    {
        [FieldOffset(0)] public MouseInput mi;
        [FieldOffset(0)] public KeyboardInput ki;
        [FieldOffset(0)] public HardwareInput hi;
    }

    [StructLayout(LayoutKind.Sequential)]
    struct MouseInput
    {
        public int dx;
        public int dy;
        public int mouseData;
        public uint dwFlags;
        public uint time;
        public IntPtr dwExtraInfo;
    }

    [StructLayout(LayoutKind.Sequential)]
    struct KeyboardInput
    {
        public ushort wVk; // 虚拟按键码
        public ushort wScan;
        public uint dwFlags; // 0 for key press, KEYEVENTF_KEYUP for key release
        public uint time;
        public IntPtr dwExtraInfo;
    }

    [StructLayout(LayoutKind.Sequential)]
    struct HardwareInput
    {
        public uint uMsg;
        public ushort wParamL;
        public ushort wParamH;
    }

    const int INPUT_KEYBOARD = 1;

    public void SendA2()
    {
        // 模拟按下方向键右键
        keybd_event(VK_A, 0x45, KEYEVENTF_EXTENDEDKEY, 0);
        Thread.Sleep(2000);
        // 模拟释放方向键右键
        keybd_event(VK_A, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
    }
    public void SendA()
    {
        // 模拟按下键盘的 "A" 键
        Input[] inputs = new Input[2];

        // 模拟按键按下
        inputs[0] = new Input
        {
            type = INPUT_KEYBOARD,
            u = new InputUnion
            {
                ki = new KeyboardInput
                {
                    wVk = 0x41, // "A" 键的虚拟按键码
                    dwFlags = 0, // 0表示按下
                }
            }
        };

        // 模拟按键松开
        inputs[1] = new Input
        {
            type = INPUT_KEYBOARD,
            u = new InputUnion
            {
                ki = new KeyboardInput
                {
                    wVk = 0x41, // "A" 键的虚拟按键码
                    dwFlags = KEYEVENTF_KEYUP, // 释放按键
                }
            }
        };

        // 发送输入事件
        SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(Input)));

        Console.WriteLine("模拟按下了'A'键");
    }
}
